package com.tenglong.teacher.ui.setting;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.clean.DataCleanManager;
import com.cuotibao.zhuoxiao.basics.utils.file.UriToPathUtil;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.dialog.PictureDialogFragment;
import com.thinkcool.circletextimageview.CircleTextImageView;
import com.yalantis.ucrop.UCrop;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserDetailsActivity extends BaseActivity {


    private ClientUserInfo userInfo;
    private CircleTextImageView mHeaderImage;
    private TextView mtTvSex, mTvSign, mTvPhone, mTvName;
    private String path;
    private Uri pictureUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_details);
        userInfo = DataState.getInstance().getUserInfo();
        initView();
        setListeners();
        initData();
    }


    private void initData() {
        setTitle(getString(R.string.user_info));
        mTvPhone.setText(userInfo.getPhone() == null ? "" : userInfo.getPhone());
        mTvName.setText(userInfo.getUserName() == null ? "" : userInfo.getUserName());
        setHeaderImage(userInfo.getPhotoUrl());
        setSex(getString(userInfo.getSex() == 1 ? R.string.user_man : R.string.user_woman));
        setSign(StringUtil.replaceBlank(userInfo.getSlogan()));
    }

    private void setSign(String sign) {
        mTvSign.setText(sign == null ? "" : sign);
    }

    private void setSex(String sex) {
        mtTvSex.setText(sex == null ? "" : sex);
    }

    private void setListeners() {
        findViewById(R.id.ly_header).setOnClickListener(this);
        findViewById(R.id.ly_sex).setOnClickListener(this);
        findViewById(R.id.ly_sign).setOnClickListener(this);
    }

    private void initView() {
        mHeaderImage = findViewById(R.id.mHeaderImage);
        mtTvSex = findViewById(R.id.tv_sex);
        mTvSign = findViewById(R.id.tv_sign);
        mTvPhone = findViewById(R.id.tv_phone);
        mTvName = findViewById(R.id.tv_name);
    }

    private void setHeaderImage(String imageUrl) {
        if (!TextUtils.isEmpty(imageUrl)) {
            RequestOptions options = GlideOptions.getGlideRequestOptions().
                    error(R.drawable.setting_image_defauft_header).
                    placeholder(R.drawable.header_image_loading);
            Log.e("headerImage",IpUtils.getImageUrl(imageUrl));
            Glide.with(this)
                    .load(IpUtils.getImageUrl(imageUrl))
                    .apply(options)
                    .into(mHeaderImage);
        } else {
            mHeaderImage.setImageResource(R.drawable.photoadd);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ly_header:
                getPhoto();
                break;
            case R.id.ly_sex:
                startActivityForResult(new Intent(this, ChangeSexActivity.class), GlobalConstant.REQUEST_CODE_CHANGE_SEX_ACTIVITY);
                break;
            case R.id.ly_sign:
                startActivityForResult(new Intent(this, ChangeSignActivity.class), GlobalConstant.REQUEST_CODE_CHANGE_SIGN_ACTIVITY);
                break;
            default:
                break;
        }
    }

    /**
     * 获取照片（展示选择获取图片方式的dialog）
     */
    private void getPhoto() {
        PictureDialogFragment.getInstance().setPictureDialogListener(new PictureDialogFragment.PictureDialogListener() {
            @Override
            public void onPhotoAlbum() {
                openPhotoAlbum();
            }

            @Override
            public void onShoot() {
                takePicture();
            }

            @Override
            public void onCancle() {
            }
        }).show(getSupportFragmentManager(), "picture");
    }


    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_PBTAIN_IMAGE);
    }


    /**
     * 打开相机
     */
    private void takePicture() {
        Intent intent;
        path = Environment.getExternalStorageDirectory() + "/cuoTiBao/";
        //设定拍照存放到自己指定的目录,可以先建好
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        File pictureFile = new File(file, System.currentTimeMillis() + ".jpg");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, pictureFile.getAbsolutePath());
            pictureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        } else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(pictureFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                pictureUri);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_SHOOT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_PBTAIN_IMAGE:
                    if (data == null) return;
                    Uri mUri = data.getData();
                    if (mUri == null) return;
                    beginCrop(mUri);
                    break;
                case GlobalConstant.REQUEST_CODE_CHANGE_SIGN_ACTIVITY:
                    setSign(userInfo.getSlogan());
                    setResult(Activity.RESULT_OK);
                    break;
                case GlobalConstant.REQUEST_CODE_CHANGE_SEX_ACTIVITY:
                    setSex(getString(userInfo.getSex() == 1 ? R.string.user_man : R.string.user_woman));
                    break;
                case UCrop.REQUEST_CROP:
                    if (data == null) return;
                    Uri cropUri = UCrop.getOutput(data);
                    if (cropUri == null) return;
                    showProgressDialog(getString(R.string.user_header_image_midifiering));
                    final Tiny.FileCompressOptions compressOptions = new Tiny.FileCompressOptions();
                    compressOptions.config = Bitmap.Config.RGB_565;
                    compressOptions.isKeepSampling = true;
                    compressOptions.compressDirectory = DataCleanManager.getHeaderImageLink(this);
                    Tiny.getInstance().source(UriToPathUtil.getImageAbsolutePath(this, cropUri)).asFile().withOptions(compressOptions).compress(new FileCallback() {
                        @Override
                        public void callback(boolean isSuccess, String outfile, Throwable t) {
                            if (!isSuccess) {
                                ToastUtils.showCenterToast("图片预处理失败");
                                dismissProgressDialog();
                                return;
                            }
                            uploadImage(outfile);
                        }
                    });
                    break;
                case GlobalConstant.REQUEST_CODE_SHOOT:
                    if (pictureUri != null) {
                        beginCrop(pictureUri);
                    }
                    break;
            }
        }
    }

    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        int size = DensityUtil.dp2px( 60);
        UCrop crop = UCrop.of(source, destination)
                .withAspectRatio(1, 1)
                .withMaxResultSize(size, size);
        Intent intent = crop.getIntent(this);
        intent.putExtra(UCrop.Options.EXTRA_TOOL_BAR_COLOR, ContextCompat.getColor(this, R.color.theme_green));
        intent.putExtra(UCrop.Options.EXTRA_STATUS_BAR_COLOR, ContextCompat.getColor(this, R.color.theme_green));
        intent.putExtra(UCrop.Options.EXTRA_UCROP_COLOR_WIDGET_ACTIVE, ContextCompat.getColor(this, R.color.theme_green));
        intent.putExtra(UCrop.Options.EXTRA_UCROP_ROOT_VIEW_BACKGROUND_COLOR, ContextCompat.getColor(this, R.color.theme_green));
        crop.start(this);
    }


    /**
     * 上传头像
     */
    private void uploadImage(String outfile) {
        File file = new File(outfile);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        CreateRequestEntity.getWebService().uploadPhotoImage(body).enqueue(new Callback<BaseResult<ClientUserInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<ClientUserInfo>> call, Response<BaseResult<ClientUserInfo>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data != null) {
                        String photoUrl = response.body().data.getPhotoUrl();
                        if (photoUrl != null && !photoUrl.equals("/uploadednull")) {
                            DataState.getInstance().getUserInfo().setPhotoUrl(photoUrl);
                            setHeaderImage(photoUrl);
                            setResult(Activity.RESULT_OK);
                        }
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<ClientUserInfo>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }

}

